<template>
  <div class="permission">
    <div class="permission-header">
      <h3 class="permission-title">角色管理</h3>
    </div>

    <div class="permission-content">
      <!-- 左侧角色列表 -->
      <div class="role-list">
        <div class="role-list-header">
          <h4 class="role-list-title">角色列表</h4>
          <el-button type="primary" size="primary" @click="addRole" v-permission="'project:manage:role:create'">
            <IconAddMember mr-4px />
            添加角色
          </el-button>
        </div>

        <div class="role-items" v-loading="isloading">
          <div v-for="role in roles" :key="role.id" class="role-item" :class="{ active: selectedRole?.id === role.id }"
            @click="selectRole(role)">
            <div class="role-info">
              <div class="role-details">
                <div class="role-name">{{ role.name }}</div>
              </div>
            </div>
            <div class="role-actions">
              <button class="action-btn" @click.stop="editRole(role)" title="编辑角色"
                v-permission="'project:manage:role:edit'" v-if="role.type !== 'admin'">
                <IconEdit />
              </button>
              <button class="action-btn" @click.stop="deleteRole(role)" title="删除角色"
                v-permission="'project:manage:role:delete'" v-if="role.type !== 'admin'">
                <IconDelete />
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧权限设置 -->
      <div class="permission-setting">
        <div class="permission-header">
          <h4 class="permission-title">{{ selectedRole?.name || '请选择角色' }}</h4>
          <el-button type="primary" size="primary" @click="updateRolePermissionTree"
            v-permission="'project:manage:role:edit'" v-if="isPermissionEditable">
            <IconUpdate class="mr-4px" />
            更新权限
          </el-button>
        </div>
        <div class="permission">
          <h3>权限配置</h3>
          <div class="permission-tree" v-loading="permissionTreeLoading">
            <el-tree v-loading="isLoading" ref="treeRef" style="max-width: 600px" :data="permissionTree" show-checkbox
              default-expand-all node-key="id" highlight-current :props="defaultProps"
              :default-checked-keys="defaultCheckedKeys" check-strictly :expand-on-click-node="false"
              @check-change="handleChangePermission"
              :class="{ 'disabled-tree': (!userStore.hasPermission('project:manage:role:edit', 'project', undefined, userStore.currentProjectId)) || !isPermissionEditable }" />
          </div>
        </div>
      </div>
    </div>
    <RoleDialog v-model="showRoleDialog" :id="roleId" :modeType="mode" @changed="getRoleList"> </RoleDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getRoleListApi, deleteRoleApi, getRolePermissionTree, updateRolePermissionTreeApi } from '@/common/apis/projectMember/index.ts';
import { useRoute } from 'vue-router';
import { useTreeCascadeCheck } from '../hooks/useTreeCascadeCheck';
import RoleDialog from './RoleDialog.vue';
import { useUserStore } from '@/store/modules/user';

// 角色数据
const roles = ref([]);
const route = useRoute();
const showRoleDialog = ref(false);
const mode = ref<string>('add');
const roleId = ref<number>(1);
const selectedRole = ref(null);
const permissionTree = ref([]);
const treeRef = ref(null);
const defaultCheckedKeys = ref([]);
const userStore = useUserStore();
const isLoading = ref(false);
const isloading = ref(false);
const permissionTreeLoading = ref(false);

const isPermissionEditable = computed(() => {
  return selectedRole.value?.type !== 'admin';
});

// 使用树形级联选中 hook
const { handleTreeChangePermission } = useTreeCascadeCheck(permissionTree, treeRef);

const defaultProps = {
  children: 'children',
  label: 'name',  // 将 'label' 改为 'name'
};

const getRoleList = async () => {
  try {
    isloading.value = true;
    const { data } = await getRoleListApi({ projectId: userStore.currentProjectId });
    roles.value = data;
  } catch (error) {
  } finally {
    isloading.value = false;
  }
};

const addRole = () => {
  mode.value = 'add';
  showRoleDialog.value = true;
};

const editRole = async (role) => {
  mode.value = 'edit';
  showRoleDialog.value = true;
  roleId.value = role.id;
};

const deleteRole = async (role) => {
  ElMessageBox.confirm(
    `确认删除角色 "${role.name}" 吗？此操作不可撤销，删除后该角色对应的成员需要重新分配角色，否则无法访问项目资源`,
    'warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await deleteRoleApi({ projectId: userStore.currentProjectId, roleId: role.id });
      ElMessage.success({ message: `${res.message}` });
      selectedRole.value=null;
      await getRoleList();
    })
    .catch(() => {
    });
};

onMounted(async () => {
  await getRoleList();
});

// 提取 checked=true 的节点 id
const extractCheckedKeys = (nodes) => {
  // 确保 nodes 是数组
  if (!Array.isArray(nodes)) {
    return [];
  }

  return nodes.reduce((acc, node) => {
    if (node.checked) {
      acc.push(node.id);
    }
    if (node.children?.length) {
      acc = acc.concat(extractCheckedKeys(node.children));
    }
    return acc;
  }, []);
};

// 更新项目角色权限树
const updateRolePermissionTree = async () => {
  if (!selectedRole.value?.id) {
    ElMessage({
      message: '请先选择角色',
      type: 'warning',
    });
    return;
  }
  try {
    permissionTreeLoading.value = true;
    const res = await updateRolePermissionTreeApi({ projectRoleId: selectedRole.value.id, permissionTree: permissionTree.value });
    ElMessage.success({ message: `${res.message}` });
  } catch (error) {
  } finally {
    permissionTreeLoading.value = false;
  }
};

// 处理节点选中状态变化（使用 hook 中的函数）
const handleChangePermission = async (data: any, checked: boolean, childChecked: boolean) => {
  // 调用 hook 中的函数
  await handleTreeChangePermission(data, checked, childChecked);
  // 更新默认选中状态
  defaultCheckedKeys.value = extractCheckedKeys(permissionTree.value);
};


watch(() => selectedRole.value, async (newValue) => {
  if (!newValue || !newValue.id) {
    // 清空数据
    permissionTree.value = [];
    defaultCheckedKeys.value = [];
    return;
  }
  try {
    isLoading.value = true;
    
    // 先清空之前的数据
    permissionTree.value = [];
    defaultCheckedKeys.value = [];
    
    const { data } = await getRolePermissionTree({
      projectRoleId: newValue.id,
      projectId: Number(route.params.id)
    }) as any;
    permissionTree.value = data;
    defaultCheckedKeys.value = extractCheckedKeys(data);
    
    // 强制更新树组件状态
    await nextTick();
    if (treeRef.value) {
      treeRef.value.setCheckedKeys(defaultCheckedKeys.value);
    }
  } catch (error) {
    console.error('获取权限树失败:', error);
    permissionTree.value = [];
  } finally {
    isLoading.value = false;
  }
}, { immediate: false });

// 方法
const selectRole = (role: any) => {
  selectedRole.value = role;
};
</script>

<style lang="less" scoped>
.permission {
  padding: 16px;
  height: 100%;
  background: var(--bg-primary);
  display: flex;
  flex-direction: column;

  .permission-header {
    margin-bottom: 16px;

    .permission-title {
      font-size: 20px;
      font-weight: 600;
      color: var(--text-primary);
    }

    .permission-desc {
      font-size: 14px;
      color: var(--text-secondary);
      margin: 0;
    }
  }

  .permission-content {
    display: flex;
    gap: 8px;
    flex: 1;

    .role-list {
      padding: 12px;
      width: 320px;
      border-radius: 8px;
      border: 1px solid var(--border-light);
      display: flex;
      flex-direction: column;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      background: var(--bg-secondary);

      .role-list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 16px;
        border-bottom: 1px solid var(--text-primary);

        .role-list-title {
          font-size: 16px;
          font-weight: 700;
          color: var(--text-primary);
          margin: 0;
          letter-spacing: 0.5px;
        }
      }

      .role-items {
        flex: 1;
        overflow-y: auto;
        overflow-x: hidden; // 添加这行，隐藏水平滚动条
        padding: 2px;

        .role-item {
          padding: 8px;
          border: none;
          margin-bottom: 2px;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: space-between;
          position: relative;
          width: 100%; // 确保宽度不超出容器
          box-sizing: border-box; // 包含边框和内边距

          // 选中状态样式 - 与 Sidebar.vue 保持一致
          &.active {
            background: var(--card-bg) !important;
            border: 2px solid var(--primary-color) !important;
            box-shadow: var(--shadow-medium) !important;
          }

          &:first-child {
            border-top-left-radius: 6px;
            border-top-right-radius: 6px;
          }

          &:last-child {
            border-bottom: none;
            border-bottom-left-radius: 6px;
            border-bottom-right-radius: 6px;
          }

          &:hover {
            background: var(--hover-bg);
            border-color: var(--border-light);
            transform: translateX(2px);

            .role-actions {
              opacity: 1;
              transform: translateX(0);
              visibility: visible;
            }
          }

          .role-info {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
            min-width: 0; // 防止内容溢出

            .role-icon {
              width: 40px;
              height: 40px;
              border-radius: 8px;
              background: var(--primary-color);
              color: white;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 18px;
            }

            .role-details {
              flex: 1;
              min-width: 0; // 防止内容溢出

              .role-name {
                font-size: 14px;
                font-weight: 600;
                color: var(--text-primary);
                margin-bottom: 4px;
                white-space: nowrap; // 防止文字换行
                overflow: hidden;
                text-overflow: ellipsis;
              }

              .role-desc {
                font-size: 12px;
                color: var(--text-secondary);
                margin-bottom: 4px;
              }

              .role-count {
                font-size: 11px;
                color: var(--text-secondary);
              }
            }
          }

          .role-actions {
            display: flex;
            align-items: center;
            gap: 8px;
            opacity: 0;
            transform: translateX(20px);
            transition: all 0.3s ease-out;
            visibility: hidden;
            flex-shrink: 0; // 防止按钮被压缩

            .action-btn {
              display: inline-flex;
              align-items: center;
              justify-content: center;
              width: 24px;
              height: 24px;
              border: 1px solid var(--border-color);
              border-radius: 6px;
              background: var(--bg-primary);
              color: var(--text-secondary);
              cursor: pointer;
              transition: all 0.2s ease;
              padding: 0;
              box-shadow: var(--shadow-light);

              :deep(svg) {
                width: 14px;
                height: 14px;
                color: var(--text-secondary);
                fill: var(--text-secondary);
              }

              &:hover {
                background: var(--primary-color);
                color: var(--bg-primary);
                border-color: var(--primary-color);
                transform: translateY(-1px);
                box-shadow: var(--hover-shadow);

                :deep(svg) {
                  color: var(--bg-primary);
                  fill: var(--bg-primary);
                }
              }

              &:active {
                transform: translateY(0);
                box-shadow: var(--shadow-light);
              }

              // 编辑按钮特殊样式
              &:first-child:hover {
                background: var(--info-color);
                border-color: var(--info-color);
              }

              // 删除按钮特殊样式
              &:last-child:hover {
                background: var(--error-color);
                border-color: var(--error-color);
              }
            }
          }
        }
      }
    }

    .permission-setting {
      flex: 1;
      padding: 16px;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      border: 1px solid var(--border-light);
      background: var(--bg-secondary);

      .permission-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .permission-title {
          font-size: 16px;
          font-weight: 700;
          color: var(--text-primary);
          margin: 0;
          letter-spacing: 0.5px;
        }
      }

      .permission {
        h3 {
          color: var(--text-primary);
        }

        .permission-tree {
          :deep(.el-tree-node) {
            background: var(--bg-primary);
          }

          :deep(.el-text .is-truncated .el-tree-node__content) {
            color: var(--bg-primary);
          }

          :deep(.el-tree-node__expand-icon) {
            display: none;
          }

          :deep(.el-tree__empty-block) {
            background: var(--bg-primary);

            :deep(.el-tree__empty-text) {
              background: var(--text-primary);
            }
          }
        }

        .member-management {
          .member-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;

            h5 {
              font-size: 14px;
              font-weight: 600;
              color: var(--text-primary);
              margin: 0;
            }
          }

          .member-list {
            .member-info {
              display: flex;
              align-items: center;
              gap: 8px;

              .member-name {
                font-weight: 500;
              }
            }
          }
        }
      }
    }
  }

  // 对话框样式
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  // 禁用树形组件的复选框 - 保持选中状态但禁用操作
  .disabled-tree {
    :deep(.el-checkbox) {
      pointer-events: none;
      opacity: 0.6;
      cursor: not-allowed !important;
    }

    :deep(.el-checkbox__input) {
      cursor: not-allowed !important;
      opacity: 0.6;
    }

    :deep(.el-checkbox__inner) {
      background-color: #f5f7fa !important;
      border-color: #dcdfe6 !important;
      cursor: not-allowed !important;
    }

    // 选中状态的复选框样式
    :deep(.el-checkbox.is-checked .el-checkbox__inner) {
      background-color: #37383a !important;
      border-color: #767d8b !important;
    }

    :deep(.el-checkbox.is-checked .el-checkbox__inner::after) {
      border-color: #d6d4d4 !important;
    }

    :deep(.el-checkbox__label) {
      color: #393a3b !important;
      cursor: not-allowed !important;
    }

    // 禁用整个树节点的点击
    :deep(.el-tree-node__content) {
      cursor: not-allowed !important;
    }

    // 禁用树节点的展开/收起
    :deep(.el-tree-node__expand-icon) {
      cursor: not-allowed !important;
      opacity: 0.6;
    }
  }
}
</style>